const express= require('express');
const routers = express.Router()
const {Order, User}= require('../schema/orderSchema')
const checkLogin = require('../middlewase/checkLogin')
const md5 = require('md5')
routers.post('/addOrder',checkLogin,(req,res)=>{
    let s = new Order(req.body)
    s.save().then(result=>{
        res.render('submitStatus',{success:1,direction:'提交成功',route:'/list',routername:'跳转到列表页面'})
    },e=>{
        res.render('submitStatus',{success:0,direction:'提交失败',route:'/addOrder',routername:"返回添加页面"})
    })
})

routers.post('/register',(req,res)=>{
    const {username, password} = req.body;
    if(username && password){
        const s = new User({...req.body, password:md5(password)})
        s.save().then(result=>{
            res.render('submitStatus',{success:1,direction:'注册成功',route:'/login',routername:"进入登录页面"})
        },e=>{
            res.render('submitStatus',{success:0,direction:'注册失败',route:'/register',routername:"返回注册页面"})
        })
    }else{
        res.render('submitStatus',{success:0,direction:'注册失败',route:'/register',routername:"返回注册页面"})
    }
    
})

routers.post('/login',(req,res)=>{
    console.log(req.body)
    let {username, password} = req.body

    User.findOne({username:username, password:md5(password)}).then((data,err)=>{
        if(data){
            req.session.username = data.username;
            // req.session._id= data._id
            // res.json({
            //     code:'2000',
            //     message:'登录成功',
            //     data:req.session.sid
            // })
            res.render('submitStatus',{success:1, direction:"登录成功",route:'/list',routername:'跳转到列表页面'})
            // res.render('index',{})
            // res.send('登录成功')
        }else{
            res.render('submitStatus',{success:0, direction:"用户名密码错误",route:'/login',routername:'返回登录页面'})
        }
        console.log(data)
    })
})
routers.post('/logout',(req,res)=>{
    if(req.session){
        req.session.destroy()
        res.render('submitStatus',{success:1, direction:"退出成功",route:'/login',routername:'跳转到登录页面'})
    }else{
        res.render('submitStatus',{success:1, direction:"登录成功",route:'/list',routername:'跳转到列表页面'})
    }

})
module.exports = routers

